#coding:utf-8
import talib
from py_at.strategy import Strategy
from py_at.Data import Data
from py_at.Bar import Bar
import numpy as np
import time
class TuPoK(Strategy):
    def __init__(self,cfg):
        super().__init__(cfg)
        #初始化参数
        if cfg=="":
            self.Params['stoplength'] = 100
            self.Params['startlength'] = 100
            self.Params['Lots'] = 1
            self.Params['Slippage'] = 0
        self.p_lots = self.Params['Lots'] = 1

        self.timeD = ''
        self.MovePrice=0

    def OnBarUpdate(self,data=Data,bar=Bar):

        if len(self.C)<max(self.Params['stoplength'],self.Params['startlength']):
            return

        startupline = talib.MAX(self.C, self.Params['startlength'])
        startdowline = talib.MIN(self.C, self.Params['stoplength'])
        # 出场条件
        stopupline = talib.MAX(self.C, self.Params['stoplength'])
        stopdowline = talib.MIN(self.C, self.Params['startlength'])
        if (self.timeD != self.D[-1]):
            self.IndexDict['startUpline'] = startupline.tolist()
            self.IndexDict['startdowline'] = startdowline.tolist()
            self.IndexDict['stopupline'] = stopupline.tolist()
            self.IndexDict['stopdowline'] = stopdowline.tolist()
            self.timeD = self.D[-1]

        # 卖平
        if self.PositionLong > 0:
            if self.C[-2] <= stopdowline[-2]:
                self.Sell(self.O[-1] - self.MovePrice, self.p_lots, '卖平')

        # 买平
        if self.PositionShort > 0:
            if self.C[-2] >= stopupline[-2]:
                self.BuyToCover(self.O[-1] - self.MovePrice, self.p_lots, '买平')

        # 买开
        if self.PositionLong == 0:
            if self.C[-2] >= startupline[-2]:
                self.Buy(self.O[-1] + self.MovePrice, self.p_lots, '买开')

        # 卖开
        if self.PositionShort == 0:
            if self.C[-2] <= startdowline[-2]:
                self.SellShort(self.O[-1] + self.MovePrice, self.p_lots, '卖开')







